package com.iflytek.cosmo.ocr.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

import com.iflytek.cosmo.ocr.common.constant.CommonConstant;
import com.iflytek.cosmo.ocr.model.domain.MessageOutput;
import com.iflytek.cosmo.ocr.model.domain.State;
import com.iflytek.cosmo.ocr.model.dto.ChangePwdParam;
import com.iflytek.cosmo.ocr.model.dto.UapOutput;
import com.iflytek.cosmo.ocr.model.dto.UserAuthOutput;
import com.iflytek.cosmo.ocr.model.dto.UserInfo;
import com.iflytek.cosmo.ocr.model.dto.UserOutput;
import com.iflytek.cosmo.ocr.service.UserInfoService;
import com.iflytek.cosmo.ocr.support.uap.UapPwdStrategy;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @ClassName: UserInfoController
 * @Description: 处理用户管理的类
 * @author yagu
 * @date 2018年5月14日
 */
@EnableSwagger2
@Api("用户管理API")
@RestController
public class UserInfoController {

	/**
	 * 日志记录器
	 */
	private final Logger logger = LoggerFactory.getLogger(UserInfoController.class);

	/**
	 * 用户服务接口
	 */
	@Resource
	private UserInfoService userInfoService;

	@Autowired
	private UapPwdStrategy uapPwdStrategy;

	/**
	 * @Title: getUserInfoById
	 * @Description: 获取当前用户信息
	 * @param userId 用户ID
	 * @return User 用户信息
	 */
	@ApiOperation(value = "获取用户信息", notes = "获取当前用户信息", httpMethod = "GET", response = MessageOutput.class)
	@RequestMapping(value = "/userId", method = RequestMethod.GET)
	public MessageOutput<UserOutput> getUserInfoById(
			@ApiParam(value = "用户ID", required = true) @RequestParam String userId) {
		logger.info("userId[userId = " + userId + "]");
		UserOutput userOutput = userInfoService.getUserInfoById(userId);
		return (userOutput != null) ? new MessageOutput<UserOutput>(new State(CommonConstant.SUCCESS_CODE), userOutput)
				: new MessageOutput<UserOutput>(
						new State(CommonConstant.FAIL_CODE, CommonConstant.QUERY_USER_ERROR_MSG));
	}

	/**
	 * @Title: getUserInfoByName
	 * @Description: 获取当前用户信息
	 * @param userName 用户名称或者MAC
	 * @return User 用户信息
	 */
	@ApiOperation(value = "获取用户信息", notes = "获取当前用户信息", httpMethod = "GET", response = UserInfo.class)
	@RequestMapping(value = "/userName", method = RequestMethod.GET)
	public MessageOutput<UserOutput> getUserInfoByName(
			@ApiParam(value = "用户名称", required = true) @RequestParam String userName) {
		logger.info("userName[userName = " + userName + "]");
		UserOutput userOutput = userInfoService.getUserInfoByName(userName);
		return (userOutput != null) ? new MessageOutput<UserOutput>(new State(CommonConstant.SUCCESS_CODE), userOutput)
				: new MessageOutput<UserOutput>(
						new State(CommonConstant.FAIL_CODE, CommonConstant.QUERY_USER_ERROR_MSG));
	}

	/**
	 * @Title: login
	 * @Description: 登陆
	 * @param user 登陆用户信息
	 * @return Message 消息
	 */
	@ApiOperation(value = "登录", notes = "输入用户名和密码登录", httpMethod = "POST")
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public MessageOutput<UserAuthOutput> login(
			@ApiParam(value = "用户登录信息", required = true) @Valid @RequestBody UserInfo user,
			HttpServletRequest request) {
		logger.info("login[user = " + user.getUsername() + ",pwd=" + user.getPwd() + "]");
		MessageOutput<UserAuthOutput> messageOutput = null;
		
		Map<String, Object> map = userInfoService.checkAndGetUserInfo(user.getUsername(), user.getPwd());
		boolean flag = (boolean) map.get("isValid");
		String message = map.get("message").toString();

		if (!flag) {
			return new MessageOutput<UserAuthOutput>(new State(CommonConstant.FAIL_CODE, uapPwdStrategy.getLoginErrorMessage(message)));
		}

		UserAuthOutput userAuthOutput = (UserAuthOutput) map.get("userInfo");
		messageOutput = new MessageOutput<UserAuthOutput>(new State(CommonConstant.SUCCESS_CODE), userAuthOutput);
		/*try {
			// 向数据分析平台推送(客户端启动次数)
			argusPostService.argusPost(ArgusConstant.SUM_INIT_TYPE, 1, userAuthOutput.getUserId(),
					userAuthOutput.getUserName(), InetAddressUtil.getRemoteIpAddr(request));
		} catch (Exception e) {
			logger.error(ArgusConstant.ARGUS_POST_FAILURES + ":" + e.getMessage());
			e.printStackTrace();
			logger.info("客户端启动人数统计推送失败！");
		}
		logger.info("客户端启动人数统计推送成功！");*/

		return messageOutput;
	}

	/**
	 * @Title: logout
	 * @Description: 注销
	 * @param userId 消息
	 */
	@ApiOperation(value = "注销", notes = "注销当前用户", httpMethod = "GET")
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public MessageOutput<Object> logout(@ApiParam(value = "用户ID", required = true) @RequestParam String userId) {
		logger.info("logout[userId = " + userId + "]");
		return new MessageOutput<Object>(new State(CommonConstant.SUCCESS_CODE));
	}

	/**
	 * @Title: register
	 * @Description: 注册
	 * @param user 注册信息
	 * @return Message 消息
	 */
	@ApiOperation(value = "注册", notes = "输入用户名和密码注册", httpMethod = "POST", response = MessageOutput.class)
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public MessageOutput<Object> register(
			@ApiParam(value = "用户注册信息", required = true) @Valid @RequestBody UserInfo user, HttpServletRequest request) {
		logger.info("register[user = " + user.getUsername() + ",pwd=" + user.getPwd() + "]");

		if (user.getPwd() == null || "".equals(user.getPwd()) || !uapPwdStrategy.pwdVerify(user.getPwd())) {
			return new MessageOutput<Object>(new State(CommonConstant.FAIL_CODE, uapPwdStrategy.getPwdErrorMessage()));
		}

		UapOutput<String> output = userInfoService.registerUser(user.getUsername(), user.getPwd());
		if (output == null) {
			return new MessageOutput<Object>(new State(CommonConstant.FAIL_CODE, CommonConstant.REGISTER_ERROR));
		}
		if (!output.getFlag()) {
			return new MessageOutput<Object>(new State(CommonConstant.FAIL_CODE, output.getMessage()));
		}

		return new MessageOutput<Object>(new State(CommonConstant.SUCCESS_CODE, output.getMessage()));
	}

	/**
	 * 修改密码
	 * @param changePwdParam 修改密码信息
	 * @return Message消息
	 */
	@ApiOperation(value = "修改密码", notes = "输入登录名及新旧密码，新旧密码为base64加密字符串", httpMethod = "POST", response = MessageOutput.class)
	@PostMapping(value = "/changePwd")
	public MessageOutput<UapOutput> changePwd(
			@ApiParam(value = "修改密码信息", required = true) @Valid @RequestBody ChangePwdParam changePwdParam) {
		MessageOutput<UapOutput> messageOutput = null;
		messageOutput = new MessageOutput<UapOutput>(
				new State(CommonConstant.SUCCESS_CODE), userInfoService.changePwd(changePwdParam));
		return messageOutput;
	}

	/**
	 * 用户验证
	 * @param userName 用户登录名
	 * @return Message消息
	 */
	@ApiOperation(value = "用户验证", notes = "输入用户名", httpMethod = "POST", response = MessageOutput.class)
	@PostMapping(value = "/userCheck")
	public MessageOutput userCheck(@ApiParam(value = "用户验证", required = true) @RequestParam String userName) {
		return new MessageOutput<>(	new State(CommonConstant.SUCCESS_CODE), userInfoService.userCheck(userName));
	}

}
